<?php 
	if (isset($_POST['gameid']) || isset($_REQUEST['recentgame'])) {
		// Delete old session
		session_start();
		session_destroy();
		// Start a new session
		include_once "db/db.php";
		
		// Load game id or recent game
		if (isset($_POST['gameid'])) {
			// Load game
			$gameid = $_POST['gameid'];
			$_SESSION['game'] = $gameid;
			// Update last opened time
			mysql_query("UPDATE `game` SET `lastopened` = '" . current_date_time() . "' WHERE `id` = '$gameid' LIMIT 1");
			// Navigate
			header("location:play.php");
		} else if (isset($_REQUEST['recentgame'])) {
			// Load game
			$gameid = mysql_result(mysql_query("SELECT `id` FROM `game` ORDER BY `lastopened` DESC LIMIT 1"), 0);
			$_SESSION['game'] = $gameid;
			// Update last opened time
			mysql_query("UPDATE `game` SET `lastopened` = '" . current_date_time() . "' WHERE `id` = '$gameid' LIMIT 1");
			// Navigate
			header("location:play.php");
		}
	}
	
	$hide_nav = true;
	include_once "header.php"; 
?>

<script type="text/javascript">
	jQuery(document).ready(function () {
		jQuery("#btnCancel").click(function () {
			window.location = "index.php";
		});
	});
</script>

<h2>Load Saved Game</h2>

<table>
	<tr>
		<th>Game name</th>
		<th>Created</th>
		<th>Last loaded</th>
		<th>Finished?</th>
		<th></th>
	</tr>
<?php
	$games_query = mysql_query("
		SELECT `game`.*, 
			COUNT(`gameplayer`.`player`) AS `players`, 
			COUNT(`gameplayer`.`retired`) AS `retirees`
		FROM `game` 
			LEFT JOIN `gameplayer` ON (`game`.`id` = `gameplayer`.`game`)
		GROUP BY `game`.`id`");
	while ($game = mysql_fetch_assoc($games_query)) {
		echo "<tr>" . 
				"<td>" . $game['name'] . "</td>" .
				"<td>" . format_date_time($game['started']) . "</td>" .
				"<td>" . format_date_time($game['lastopened']) . "</td>" .
				"<td>" . ($game['retirees'] == $game['players'] ? "Yes, all " . $game['retirees'] . " players retired" : "No, " . ($game['players'] - $game['retirees']) . " of " . $game['players'] . " players yet to retire") . "</td>" .
				"<td>" .
					"<form action=\"load.php\" method=\"post\">" .
						"<input type=\"hidden\" name=\"gameid\" value=\"" . $game['id'] . "\"/>" .
						"<input type=\"submit\" value=\"Load\"/>" .
					"</form>" .
				"</td>" .
			"</tr>\n";
	}
?>
	<tr>
		<td colspan="5" class="actions">
			<input type="reset" value="Cancel" id="btnCancel"/>
		</td>
	</tr>
</table>

<?php include_once "footer.php"; ?>
